#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_pwm.h"

#define LED_BLUE   HI_GPIO_IDX_8   // Blue 
#define LED_RED    HI_GPIO_IDX_2   // Red
#define LED_GREEN  HI_GPIO_IDX_7   // Green

#define PWM_DUTY_UP   0
#define PWM_DUTY_DOWN 1


static void LedPwmMain( void ) {
    int dutyValue = 0; //0-100
    int dutyFlag  = PWM_DUTY_UP; //up or down

    IoTGpioInit( LED_BLUE );
    hi_io_set_func( LED_BLUE, HI_IO_FUNC_GPIO_8_PWM1_OUT );
    IoTGpioSetDir( LED_BLUE, IOT_GPIO_DIR_OUT );

    IoTGpioInit( LED_RED );
    hi_io_set_func( LED_RED, HI_IO_FUNC_GPIO_2_PWM2_OUT );
    IoTGpioSetDir( LED_RED, IOT_GPIO_DIR_OUT );

    IoTGpioInit( LED_GREEN );
    hi_io_set_func( LED_GREEN, HI_IO_FUNC_GPIO_7_PWM0_OUT );
    IoTGpioSetDir( LED_GREEN, IOT_GPIO_DIR_OUT );

    IoTPwmInit( HI_PWM_PORT_PWM1 );
    IoTPwmInit( HI_PWM_PORT_PWM2 );
    IoTPwmInit( HI_PWM_PORT_PWM0 );

    printf("PWM Led Init OK\r\n");

    int m = 0;

    while (1) {
 if(dutyFlag == PWM_DUTY_UP ){
             dutyValue++;
 }
 else {
             dutyValue--;
 }

        if( dutyValue >= 100 ){
            printf("Led On to Off\r\n");
     dutyFlag = PWM_DUTY_DOWN;
 }

 if( dutyValue <= 0 ){
            printf("Led Off to On\r\n");
     dutyFlag = PWM_DUTY_UP;
     m = (m+1)%3;
 }

     IoTPwmStart( m , dutyValue, 40000);

 osDelay(3);
    }

    return ;
}

SYS_RUN( LedPwmMain );
